import axios from "axios";

import {
    Notification
} from "element-ui";
import router from "../router";

const durationTime = 3000;

axios.defaults.baseURL = "/api";

const request = axios.create({
    //    baseURL: http://192.168.31.97:9011,
    timeout: 30000,
});

//请求拦截器
request.interceptors.request.use((config) => {

    if (window.sessionStorage.getItem("OaAuth")) {
        config.headers["token-name"] = window.sessionStorage.getItem("OaAuth");
    }

    return config;
});

//响应拦截器
request.interceptors.response.use(
    function (response) {
        console.log("请求响应：", response)
        // 浏览器状态码
        let resStatus = response.status
        // 自定义状态码
        let resCode = response.data.code

        // 参数错误
        if (resStatus === 200 && resCode === 400) {
            Notification.success({
                message: response.data.message,
                duration: durationTime,
            });

            return Promise.reject(response.data)
        }
        // 权限不足
        else if (resStatus === 200 && resCode === 403) {
            const msg = response.data.message
            if (msg.includes('未提供有效')) {
                Notification.error({
                    message: "登录已过期，请重新登录",
                    duration: durationTime,
                });
            } else {
                Notification.error({
                    message: msg,
                    duration: durationTime,
                });
            }
            setTimeout(() => {
                router.replace("/login")
            }, 700);
            return Promise.reject(response.data)
        }
        // else if()
        // 服务器内部错误
        else if (resStatus === 200 && resCode === 500) {
            Notification.error({
                message: "服务器内部错误",
                duration: durationTime,
            });

            return Promise.reject(response.data)
        } else {
            if (resCode !== 200) {
                Notification.error({
                    message: "未知错误，请联系管理员",
                    duration: durationTime,
                });
                return Promise.reject(response.data)
            }
        }

        return Promise.resolve(response.data);
    },
    function (error) {
        console.log("响应失败：", error.response)
        let respStatus = error.response.status;

        if (respStatus && respStatus === 500) {
            Notification.error({
                message: "服务器内部错误，请联系管理员",
                duration: durationTime,
            });
        }

        // return;
        return Promise.reject(error);
    }
);

export default request;

// let base="http://localhost:8888"

// export const doPost = (url, params) => {
//     return axios({
//         method: 'post',
//         url: `${base}${url}`,
//         data: params
//     })
// }

// export const doGet = (url, params) => {
//     return axios({
//         method: 'get',
//         url: `${base}${url}`,
//         data: params
//     })
// }